<script setup lang="tsx">
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { Search } from '@/components/Search'
import { ContentDetailWrap } from '@/components/ContentDetailWrap'
import { watch, inject, reactive, Ref, ref, unref } from 'vue'
import { useValidator } from '@/hooks/web/useValidator'
import { Table } from '@/components/Table'
import { Row, getListGoodsApi } from '@/api/warehouse'
import { useTable } from '@/hooks/web/useTable'
import { useSearch } from '@/hooks/web/useSearch'
import { searchGoodsCateApi } from '@/api/utils/search'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
const { required } = useValidator()
const emit = defineEmits(['close', 'get-list'])
const currentRow: Ref<Row> = inject('currentRow') as Ref<Row>
const { formRegister, formMethods } = useForm()

const { setValues } = formMethods
const { searchRegister, searchMethods } = useSearch()
const { setSchema } = searchMethods
const searchUser = async (query) => {
  if (query && Object.values(query).every((item) => item !== '')) {
    setSchema([
      {
        field: 'goods_id',
        path: 'componentProps.loading',
        value: true
      }
    ])
    const params = {
      ...query,
      field: 'id,name'
    }
    const res = await searchGoodsCateApi(params)
    if (res) {
      setSchema([
        {
          field: 'goods_id',
          path: 'componentProps.options',
          value: res.data.list.map((item) => {
            return {
              label: item.goods.name,
              value: item.goods.id
            }
          })
        }
      ])
    }
    setSchema([
      {
        field: 'goods_id',
        path: 'componentProps.loading',
        value: false
      }
    ])
  }
}
const schema = reactive<FormSchema[]>([
  {
    field: '',
    label: '基础信息',
    component: 'Divider',
    colProps: { span: 28 },
    componentProps: {
      borderStyle: 'none',
      contentPosition: 'left'
    }
  },
  {
    field: 'name',
    label: '公司名称',
    component: 'Input',
    formItemProps: {
      rules: [required(), { min: 1, max: 50, message: '最多输入50个字符', trigger: 'blur' }]
    },
    componentProps: {
      placeholder: '请输入(最多50个字符)'
    }
  },
  {
    field: 'real_name',
    label: '负责人',
    component: 'Input',
    formItemProps: {
      rules: [required(), { min: 1, max: 50, message: '请输入最多支持50字符', trigger: 'blur' }]
    },
    componentProps: {
      placeholder: '请输入(最多50个字符)'
    }
  },
  {
    field: 'mobile',
    label: '联系方式',
    component: 'Input',
    formItemProps: {
      rules: [
        required(),
        { min: 11, max: 11, message: '请输入负责人联系方式', trigger: 'blur' },
        {
          pattern: /^[1][3,4,5,6,7,8,9][0-9]{9}$/,
          message: '请输入负责人联系方式',
          trigger: 'blur'
        }
      ]
    }
  },
  {
    field: 'address',
    label: '仓库地址',
    component: 'Input',
    formItemProps: {
      rules: [required(), { min: 1, max: 100, message: '最多输入100个字符', trigger: 'blur' }]
    },
    componentProps: {
      placeholder: '请输入(最多100个字符)'
    }
  },
  {
    field: 'acreage',
    label: '仓库面积m²',
    component: 'Input',
    formItemProps: {
      rules: [{ min: 0.01, message: '请输入', trigger: 'blur' }]
    },
    componentProps: {
      placeholder: '请输入(最小支持小数点后两位)'
    }
  },
  {
    field: 'long',
    label: '仓库经度',
    component: 'Input',
    formItemProps: {
      rules: [
        {
          pattern:
            /^-?((0|[1-9]\d?|([1-9]\d(\.\d{1,6})?))|([1-9]\d{0,2}(\.\d{1,6})?)|([1-8]\d{0,2}(\.\d{1,6})?)|(90(\.0{1,6})?))$/,
          message: '请输入有效的经度',
          trigger: 'blur'
        }
      ]
    },
    componentProps: {
      placeholder: '请输入经度'
    }
  },
  {
    field: 'lat',
    label: '仓库纬度',
    component: 'Input',
    formItemProps: {
      rules: [
        {
          pattern:
            /^-?((0|[1-9]\d?|([1-9]\d(\.\d{1,6})?))|([1-9]\d{0,2}(\.\d{1,6})?)|([1-8]\d{0,2}(\.\d{1,6})?)|(90(\.0{1,6})?))$/,
          message: '请输入有效的纬度',
          trigger: 'blur'
        }
      ]
    },
    componentProps: {
      placeholder: '请输入纬度'
    }
  },
  {
    field: '',
    label: '库区库位信息',
    component: 'Divider',
    colProps: { span: 28 },
    componentProps: {
      borderStyle: 'none',
      contentPosition: 'left'
    }
  },
  {
    field: 'area_num',
    label: '库区数量',
    component: 'Input',
    formItemProps: {
      rules: [required(), { min: 1, max: 50, message: '最多输入50个字符', trigger: 'blur' }]
    },
    componentProps: {
      placeholder: '请输入(最多50个字符)'
    }
  },
  {
    field: 'storage_num',
    label: '库位数量',
    component: 'Input',
    formItemProps: {
      rules: [required(), { min: 1, max: 50, message: '请输入最多支持50字符', trigger: 'blur' }]
    },
    componentProps: {
      placeholder: '请输入(最多50个字符)'
    }
  },
  {
    field: 'storage_used_num',
    label: '已使用库位数',
    component: 'Input',
    formItemProps: {
      rules: [required()]
    }
  },
  {
    field: 'storage_unused_num',
    label: '未使用库位数',
    component: 'Input',
    formItemProps: {
      rules: [required(), { min: 1, max: 100, message: '最多输入100个字符', trigger: 'blur' }]
    },
    componentProps: {
      placeholder: '请输入(最多100个字符)'
    }
  },
  {
    field: '',
    label: '库存信息',
    component: 'Divider',
    colProps: { span: 28 },
    componentProps: {
      borderStyle: 'none',
      contentPosition: 'left'
    }
  }
])
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'goods_id',
    label: '商品名称',
    search: {
      component: 'Select',
      componentProps: {
        placeholder: '支持模糊搜索',
        filterable: true,
        remote: true,
        loading: false,
        remoteMethod: (name) => searchUser({ name }),
        options: [],
        on: {
          change: (val) => {
            searchParams.value.goods_id = val
          }
        }
      }
    },
    form: { hidden: true },
    detail: { hidden: true },
    formatter: (cellValue) => {
      return cellValue.goods.name
    }
  },
  {
    field: 'goods.unit',
    label: '单位',
    search: { hidden: true },
    form: { hidden: true },
    detail: { hidden: true }
  },
  {
    field: 'goods.spec_name',
    label: '规格',
    search: { hidden: true },
    form: { hidden: true },
    detail: { hidden: true }
  },
  {
    field: 'imgList',
    label: 'LOGO',
    width: '100px',
    search: { hidden: true },
    form: { hidden: true },
    detail: { hidden: true }
  },
  {
    field: 'warehouse_area_name',
    label: '所属库区',
    search: { hidden: true },
    form: { hidden: true },
    detail: { hidden: true }
  },
  {
    field: 'warehouse_storage_name',
    label: '所属库位',
    search: { hidden: true },
    form: { hidden: true },
    detail: { hidden: true }
  },
  {
    field: 'quantity',
    label: '库存',
    search: { hidden: true },
    form: { hidden: true },
    detail: { hidden: true }
  }
])
// @ts-ignore
const { allSchemas } = useCrudSchemas(crudSchemas)
const searchParams = ref({})
const setSearchParams = (params: any) => {
  searchParams.value = params
  getList()
}

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await getListGoodsApi({
      page: unref(currentPage),
      limit: unref(pageSize),
      warehouse_id: currentRow.value.id,
      ...unref(searchParams)
    })
    return {
      list: res.data.list.map((val) => {
        const resultArray = val.goods.img.split(',')
        return {
          ...val,
          imgList: resultArray[0]
        }
      }),
      total: res.data.count
    }
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList } = tableMethods
watch(
  () => currentRow.value,
  (currentRow) => {
    if (!currentRow) return
    getList()
    setValues(currentRow)
  },
  {
    deep: true,
    immediate: true
  }
)
</script>

<template>
  <ContentDetailWrap title="仓库详情">
    <Form @register="formRegister" :schema="schema" />
    <Search
      @register="searchRegister"
      :schema="allSchemas.searchSchema"
      @search="setSearchParams"
      @reset="setSearchParams"
    />
    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total
      }"
      :image-preview="['imgList']"
      @register="tableRegister"
    />
    <template #footer>
      <div class="w-full flex items-center justify-center">
        <BaseButton @click="emit('close')">返回</BaseButton>
      </div>
    </template>
  </ContentDetailWrap>
</template>
